package com.taiyi.renaissancemall.ui.main.order

import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.View.*
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alipay.sdk.app.PayTask
import com.taiyi.renaissancemall.R
import com.taiyi.renaissancemall.Utils.PayResult
import com.taiyi.renaissancemall.Utils.ToastUtils
import com.taiyi.renaissancemall.Utils.loadCircle
import com.taiyi.renaissancemall.adapter.AdapterManager
import com.taiyi.renaissancemall.base.BaseActivity
import com.taiyi.renaissancemall.base.MyApp
import com.taiyi.renaissancemall.bean.*
import com.taiyi.renaissancemall.ui.main.paysuccess.PaySuccessActivity
import com.taiyi.renaissancemall.ui.mine.address.ShippingAddressActivity
import com.tencent.mm.opensdk.modelpay.PayReq
import kotlinx.android.synthetic.main.activity_fill_order.*
import kotlinx.android.synthetic.main.base_top_white_background_layout.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.text.DecimalFormat


class FillOrderActivity : BaseActivity<FillOrderView, FillOrderPresent>(), FillOrderView {
    var shopCarIds = ""
    var payMethod = "2"
    var sb = StringBuffer()
    var aliPayOrderId = ""
    var selCommSpecId = ""
    override fun getLayoutId(): Int = R.layout.activity_fill_order


    override fun initPresenter(): FillOrderPresent = FillOrderPresent()

    var selAddressId: String = ""

    override fun initViews(savedInstanceState: Bundle?) {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        EventBus.getDefault().register(this)
        shopCarIds = intent.getStringExtra("shopCarIds")
        titleTv.text = getString(R.string.fillOrder)
        aliPayTv.isSelected = true
        showProgress()
        presenter.getOrderInfo()
    }

    @Subscribe
    fun refreshData(address: AddressListBean.AddresslistBean) {
        if (selAddressId == "") {
            selectShippingAddressTv.visibility = INVISIBLE
            groupP.visibility = VISIBLE
        }
        selAddressId = address.useraddress_id
        Log.i("addressType", "-------" + address.type)
        if (address.type == "0") {
            defaultTv.visibility = GONE
            defaultOneTv.visibility = VISIBLE
        } else {
            defaultTv.visibility = VISIBLE
            defaultOneTv.visibility = GONE
        }
        nameTv.text = address.name
        phoneNumberTv.text = getString(R.string.contactNumber) + " " + address.tel
        shippingAddressTv.text =
            address.provincename + address.cityname + address.areaname + address.address
        presenter.getFreight()
    }

    override fun initData() {

    }

    @Subscribe
    fun paySuccess(s: String) {
        if (s.startsWith("paySuccess")) {
            showProgress()
            presenter.findOrderState()
        }
    }

    override fun initEvent() {
        backIv.setOnClickListener {
            finish()
        }
        phoneNumberTv.setOnClickListener {
            startActivity(Intent(this, ShippingAddressActivity::class.java))
        }
        selectShippingAddressTv.setOnClickListener {
            startActivity(Intent(this, ShippingAddressActivity::class.java))
        }
        aliPayTv.setOnClickListener {
            payMethod = "2"
            aliPayTv.isSelected = true
            weChatTv.isSelected = false
            balancePaymentTv.isSelected = false
        }
        weChatTv.setOnClickListener {
            payMethod = "1"
            aliPayTv.isSelected = false
            weChatTv.isSelected = true
            balancePaymentTv.isSelected = false
        }
        balancePaymentTv.setOnClickListener {
            payMethod = "3"
            aliPayTv.isSelected = false
            weChatTv.isSelected = false
            balancePaymentTv.isSelected = true
        }
        submitOrdersTv.setOnClickListener {
            if (selAddressId == "") {
                ToastUtils.showLongToast("请选择收货地址")
                return@setOnClickListener
            }
            showProgress()
            presenter.commitOrder()
        }
        editAddressIv.setOnClickListener {
            startActivity(Intent(this, ShippingAddressActivity::class.java))
        }

    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar.titleBar(top).init()
    }

    val SDK_PAY_FLAG = 1001

    override fun getRemark(): String = orderRemarksContentEt.text.toString()

    override fun getOrderStateSuccess() {
        hideProgress()
        var intent = Intent(this, PaySuccessActivity::class.java)
        intent.putExtra("payWay", payMethod)
        intent.putExtra("payAmount", totalPrice)
        intent.putExtra("orderId", aliPayOrderId);
        startActivity(intent)
        finish()
    }

    override fun getOrderStateFailure(msg: String?) {
        hideProgress()
        toast(msg)
    }

    var totalPrice = ""
    override fun getNum(): String = "1"
    override fun getFreightSuccess(freightBean: FreightBean?) {
        if (freightBean != null) {
            freightTv.text = "￥" + freightBean?.sumyunfei

            val decimalFormat: String =
                DecimalFormat("0.0").format((realPrice + freightBean.sumyunfei?.toDouble()!!))

            realPaymentTv.text = "￥$decimalFormat"
            totalPrice = decimalFormat
        } else {
            totalPrice = realPrice.toString()
            realPaymentTv.text = "￥$realPrice"
        }
    }

    override fun getFreightFailure(msg: String?) {
        toast(msg)
    }

    override fun commitOrderFailure(msg: String?) {
        hideProgress()
        ToastUtils.showLongToast(msg)
    }

    override fun getOrderId(): String = aliPayOrderId

    override fun getShopCarId(): String = shopCarIds
    override fun commitOrderSuccess(commitOrderBean: CommitOrderBean?) {
        hideProgress()
        aliPayOrderId = commitOrderBean?.orderid!!
        if ("2" == payMethod) {//支付宝支付
            val stInfo = commitOrderBean?.aliparam
            var payRunnable = Runnable {
                var alipay = PayTask(this)
                var result = alipay.payV2(stInfo, true)
                var msg = Message()
                msg.what = SDK_PAY_FLAG
                msg.obj = result
                mHandler.sendMessage(msg)
            }
            var payThread = Thread(payRunnable)
            payThread.start()

        } else if ("3" == payMethod) {//余额支付
            showProgress()
            presenter.findOrderState();
        } else if ("1" == payMethod) {//微信支付
            //这里的appid，替换成自己的即可
            var api = MyApp.getWxApi()
            api.registerApp(MyApp.getAppId());
            //这里的bean，是服务器返回的json生成的bean
            var payRequest = PayReq();
            payRequest.appId = commitOrderBean.appid
            payRequest.partnerId = commitOrderBean.partnerid
            payRequest.prepayId = commitOrderBean.prepayid
            payRequest.packageValue = "Sign=WXPay";//固定值
            payRequest.nonceStr = commitOrderBean.noncestr
            payRequest.timeStamp = commitOrderBean.timestamp
            payRequest.sign = commitOrderBean.sign

            //发起请求，调起微信前去支付
            api.sendReq(payRequest);
        }


    }


    private val mHandler: Handler = object : Handler() {

        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    var payResult = PayResult(msg.obj as MutableMap<String, String>?)
                    var resultInfo = payResult.result
                    if (payResult?.resultStatus == "9000") {
                        showProgress()
                        presenter.findOrderState()
                    }

                }
                else ->
                    ToastUtils.showLongToast("支付异常")
            }

        }
    }

    var decimalFormat = DecimalFormat("#0.00");
    override fun getAddressId(): String = selAddressId

    override fun getPayType(): String = payMethod
    override fun getProductOrderInfoSuccess(productFillOrderBean: ProductFillOrderBean?) {

    }


    var realPrice = 0.0
    override fun getOrderInfoSuccess(toFillOrderBean: ToFillOrderBean?) {
        hideProgress()
        var liquannumti = toFillOrderBean?.user?.liquannumti
        availableBalanceTv.text = "(可用余额$liquannumti)"
        var ifhui = toFillOrderBean?.ifhui


        var product1 = toFillOrderBean?.product
        for (index in 0 until product1!!.size) {
            var details = product1[index].details
            for (ind in 0 until details.size) {
                if ("1" == ifhui) {
                    realPrice += details[ind].hyprice * details[ind].number
                } else {
                    realPrice += details[ind].price * details[ind].number
                }
                sb.append("," + details[ind].commodityspecid)
            }
        }
        realPaymentTv.text = realPrice.toString()
        selCommSpecId = sb.substring(1)
//        realPaymentTv.text = "￥" + decimalFormat.format(realPrice)

        var addressParams = toFillOrderBean?.addressParams
        if (addressParams == null) {
            selectShippingAddressTv.visibility = VISIBLE
            groupP.visibility = INVISIBLE
        } else {
            groupP.visibility = VISIBLE
            selectShippingAddressTv.visibility = INVISIBLE
            selAddressId = addressParams.useraddress_id
            nameTv.text = addressParams.name
            phoneNumberTv.text = getString(R.string.contactNumber) + " " + addressParams.tel
            shippingAddressTv.text =
                addressParams.provincename + addressParams.cityName + addressParams.areaName + addressParams.address
            presenter.getFreight()
        }

        var product = toFillOrderBean?.product
        recyclerView.run {
            layoutManager = LinearLayoutManager(this@FillOrderActivity)
            adapter = MyAdapter(this@FillOrderActivity, product!!, toFillOrderBean?.ifhui)
        }
    }

    override fun getProductOrderInfoFailure(msg: String?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun getCommSpecId(): String = selCommSpecId

    inner class MyAdapter(
        var context: Context,
        var data: MutableList<ToFillOrderBean.ProductBean>,
        var ifhui: String?
    ) :
        RecyclerView.Adapter<MyAdapter.MyHolder>() {
        var layoutInflater: LayoutInflater = LayoutInflater.from(context)

        inner class MyHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val iv = itemView.findViewById<ImageView>(R.id.iv)
            val nameTv = itemView.findViewById<TextView>(R.id.nameTv)
            val selectTv = itemView.findViewById<TextView>(R.id.selectTv)
            val recyclerView = itemView.findViewById<RecyclerView>(R.id.recyclerView)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
            var view = layoutInflater.inflate(R.layout.new_shopping_car_item_layout, parent, false)
            return MyHolder(view)
        }

        override fun getItemCount(): Int = when (data) {
            null -> 0
            else
            -> data.size
        }

        override fun onBindViewHolder(holder: MyHolder, position: Int) {
            holder.iv.loadCircle(data[position].logo)
            var detailList = data[position].details
            holder.selectTv.visibility = GONE
            holder.nameTv.text = data[position].businessname
            holder.recyclerView.run {
                layoutManager = LinearLayoutManager(context)
                adapter =
                    AdapterManager.getShoppingCarListAdapter(
                        this@FillOrderActivity,
                        detailList!!,
                        ifhui
                    )
            }


        }
    }

    override fun getOrderInfoFailure(msg: String?) {
        ToastUtils.showLongToast(msg)
    }
}
